package org.hdax.controller;

import org.hdax.entity.Role;
import org.hdax.entity.Users;
import org.hdax.service.RoleService;
import org.hdax.service.UsersService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/users")
public class UsersController {
    @Autowired
    private UsersService usersService;
    @Autowired
    private RoleService roleService;


    @RequestMapping(value = "/login")
    public String login(Users users, HttpSession session){
        Users loginUsers = usersService.login(users);
//        for (RolePermission rolePermission:
//             loginUsers.getRole().getRolePermissionList()) {
//            System.out.println(rolePermission.getPermission().getTitle());
//        }
        if(loginUsers!=null){
            session.setAttribute("loginUser",loginUsers);
        }
        return "redirect:/index";
    }

    @RequestMapping("/index")
    public String index(){
        return "user/list";
    }

    @RequestMapping(value = "/list",method = RequestMethod.POST)
    @ResponseBody
    public Map<String,Object> list(@RequestParam("offset")int offset,@RequestParam("limit")int limit,Users condition){
        Map<String,Object> map = new HashMap<String, Object>();
        List<Users> users = usersService.getByPage(offset,limit,condition);
        int count = usersService.getCount(condition);
        map.put("total",count);
        map.put("rows",users);
        return map;
    }

    @RequestMapping(value = "edit/{id}",method = RequestMethod.GET)
    public String toEdit(@PathVariable("id")int id, HttpServletRequest request){
        Users users = usersService.getById(id);
        List<Role> roles = roleService.getAll();
        if(users!=null){
            request.setAttribute("users",users);
            request.setAttribute("roles",roles);
        }
        return "user/edit";
    }

    @RequestMapping(value = "edit",method = RequestMethod.POST)
    @ResponseBody
    public Map<String,Object> doEdit(Users users){
        Map<String,Object> map = new HashMap<String, Object>();
        boolean isUpdate = usersService.updateUsers(users);
        if(isUpdate) map.put("result",true);
        else map.put("result",false);
        return map;
    }
}
